package com.tangsm.spring.boot.captcha.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tangsm.spring.boot.captcha.config.KaptchaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

@Controller
public class KaptchaController {


    @Autowired
    private KaptchaConfig kaptchaConfig;

    /**
     * 创建验证码
     *
     * @throws Exception
     */
    @GetMapping("/validata/code/{client_id}")
    public void createCode(@PathVariable String client_id, HttpServletResponse response) throws Exception {
        DefaultKaptcha kaptcha = kaptchaConfig.getDDefaultKaptcha();
        Assert.notNull(client_id, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = kaptcha.createText();
        //生成图片验证码
        BufferedImage image = kaptcha.createImage(text);
        //validateCodeService.saveImageCode(client_id, text);//验证码保存方式根据个人想法实现
        try (
                ServletOutputStream out = response.getOutputStream()
        ) {
            ImageIO.write(image, "JPEG", out);
        }
    }

}
